//
//  JYTNFCCoreTool.m
//  JYTNFCCore
//
//  Created by 九爷 on 2024/1/17.
//

#import "JYTNFCCoreTool.h"

#import <LYExtension/LYExtension.h>

static JYTNFCCoreTool *_instance = nil;

NSString *const JYT_NFC_TAG_CARD_AID_JTB = @"A000000632010105";
NSString *const JYT_NFC_TAG_CARD_AID_LOCAL = @"A0000000038698070";

@implementation JYTNFCCoreTool

- (instancetype)init {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super init];
    });
    return _instance;
}

+ (id)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

- (id)copyWithZone:(nullable NSZone *)zone {
    return _instance;
}

- (id)mutableCopyWithZone:(nullable NSZone *)zone {
    return _instance;
}

+ (instancetype)instance {
    return [[self alloc] init];
}

- (void)setDebugEnv:(BOOL)debugEnv {
    _isDebugEnv = debugEnv;
}

//将字符串转NSData
+ (NSData *)convertHexStrToData:(NSString *)str {
    if (!str || [str length] == 0) {
        return nil;
    }
    
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
    NSRange range;
    if ([str length] % 2 == 0) {
        range = NSMakeRange(0, 2);
    } else {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        
        range.location += range.length;
        range.length = 2;
    }
    return hexData;
}

//NSData转字符串
+ (NSString *)convertApduListDataToHexStr:(NSData *)data {
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    return [string uppercaseString];
}

+ (NSString *)sortParam:(NSDictionary *)orginParam {
    if ([orginParam allKeys].count == 0) {
        return @"{}";
    }
    NSMutableString *contentString = [NSMutableString string];
    NSArray *keys = [orginParam allKeys];
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//        return [obj1 compare:obj2 options:NSCaseInsensitiveSearch];
        return [obj1 compare:obj2];
    }];
    
    for (NSString *key in sortedArray) {
        [contentString appendFormat:@"\"%@\":\"%@\",", key, orginParam[key]];
    }
    
    [contentString replaceCharactersInRange:NSMakeRange(contentString.length - 1, 1) withString:@""];
    return [NSString stringWithFormat:@"{%@}", contentString];
}

+ (NSString *)signStr:(NSMutableDictionary*)dict {
    NSMutableString *contentString = [NSMutableString string];
    NSArray *keys = [dict allKeys];
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if ([[dict objectForKey:categoryId] isKindOfClass:NSString.class]) {
            [contentString appendFormat:@"%@=%@&", categoryId, [NSString lyFormatStr:[dict objectForKey:categoryId]]];
        } else {
            if ([[dict objectForKey:categoryId] isKindOfClass:NSDictionary.class]) {
                [contentString appendFormat:@"%@=%@&", categoryId, [self sortParam:[dict objectForKey:categoryId]]];
            }
        }
    }
    [contentString appendFormat:@"key=%@", @"chezaijitogprs"];
    return [[contentString copy] md5String];
}

@end
